package com.edward.volleydemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

public class JsonRequestActivity extends AppCompatActivity {

    private TextView tvResult;

    private RequestQueue mRequestQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_request);

        tvResult = (TextView) findViewById(R.id.tv_result);


        //1.创建 RequestQueue
        mRequestQueue = Volley.newRequestQueue(this);
    }

    public void loadData(View view) {
        //2.创建JsonRequest对象

        //使用JsonObjectRequest,会出现乱码
        /*
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                Request.Method.GET,
                "http://www.weather.com.cn/data/sk/101010100.html",
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        if (jsonObject == null)
                            return;

                        //此处会有乱码
                        tvResult.setText(jsonObject.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        tvResult.setText(volleyError.getMessage());
                    }
                }

        );
        */

        //使用自定义JsonObjectRequest_utf8 ,进行转码
        JsonObjectRequest_utf8 jsonObjectRequest_utf8 = new JsonObjectRequest_utf8(
                Request.Method.GET,
                "http://www.weather.com.cn/data/sk/101010100.html",
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        if (jsonObject == null)
                            return;

                        //此处会有乱码
                        tvResult.setText(jsonObject.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        tvResult.setText(volleyError.getMessage());
                    }
                }
        );


        //3.添加Request对象到RequestQueue
        mRequestQueue.add(jsonObjectRequest_utf8);
    }
}
